<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-row>
      <a-col :flex="1">
        <a-form
          :model="query"
          :label-col-props="{ span: 6 }"
          :wrapper-col-props="{ span: 18 }"
          label-align="left"
        >
          <a-row :gutter="16">
            <a-col :span="8">
              <a-range-picker v-model="query.range_date" allow-clear/>
            </a-col>
            <a-col :span="4">
              <a-space :size="5">
                <a-button type="primary" @click="search"><template #icon><icon-search /></template>搜索</a-button>
                <a-button status="success" @click="refresh()"><template #icon><icon-refresh /></template>重置</a-button>
              </a-space>
            </a-col>
            <a-col :span="12" style="text-align: right">
              <file-upload :show-file-list="false" accept="*" :is-button="true" button-text="上传" @uploadCallback="uploadCallback"/>
            </a-col>
          </a-row>
        </a-form>
      </a-col>
    </a-row>
    <a-divider style="margin-top: 10px"/>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <div class="custom-checkbox-card">
            <a-checkbox v-model="checkAll" :indeterminate="checkedAllInd" @change="customSelectAll">全选</a-checkbox>
          </div>
          <a-button @click="isActivate(selectionKeys, 1)">启用</a-button>
          <a-button status="warning" @click="isActivate(selectionKeys, 0)">禁用</a-button>
          <a-button type="primary" status="danger" @click="batchDel()">
            <template #icon><icon-delete /></template>批量删除
          </a-button>
        </a-space>
      </a-col>
    </a-row>

    <a-row>
      <a-col :span="3">
        <a-card title="" style="margin-right: 10px">
          <div class="text item">文件夹：</div>
          <div class="text item">
            <a-link :class="query.folder==='' ? 'active' : 'deactive'" :disabled="(query.folder==='') ? true : false" @click="filterSelect('', query.file_type)">全部</a-link>
          </div>
          <div class="text item" v-for="folder in folders" :key="folder" >
            <a-link :class="query.folder===folder ? 'active' : 'deactive'" :disabled="(query.folder===folder) ? true : false" @click="filterSelect(folder, query.file_type)">{{ folder }}</a-link>
          </div>

          <div class="text item" style="margin-top: 20px">类型：</div>
          <div class="text item">
            <a-link :class="query.file_type==='' ? 'active' : 'deactive'" :disabled="(query.file_type==='') ? true : false" @click="filterSelect(query.folder, '')">全部</a-link>
          </div>
          <div class="text item" v-for="(item, index) in fileTypes" :key="index">
            <a-link :class="query.file_type===index.toString() ? 'active' : 'deactive'" :disabled="(query.file_type==index.toString()) ? true : false" @click="filterSelect(query.folder, index)">{{ item }}</a-link>
          </div>
        </a-card>
      </a-col>
      <a-col v-if="pagination.total > 0" :span="21" :style="fileBoxStyle">
        <a-checkbox-group v-model="checkedIds" @change="selectGroup">
          <a-grid :cols="6" :colGap="10" :rowGap="10">
            <a-grid-item v-for="(item, index) in renderData" :key="index" style="margin-bottom:6px; text-align:center">
              <a-card class="file-card" title="" :body-style="{ minWidth:'16.5%', padding:'0 6px' }">
                <div class="file-ext">
                  <span>{{ item.file_ext }}</span>
                </div>
                <div class="file-header" style="text-align: left">
                  <a-checkbox :value="item.id">{{ item.id }}</a-checkbox>
                </div>
                <div class="file-content" :style="{width:'100%', height:((height-height*0.1)/3)-((height-height*0.1)/3*0.45)+'px'}">
                  <a-image v-if="item.file_type === 'image'" :src="item.full_file_url" style="height:100%;"/>
                  <video v-else-if="item.file_type === 'video'" width="100%" height="100%" controls>
                    <source :src="item.full_file_url" type="video/mp4">
                    <object :data="item.full_file_url" width="100%" height="100%">
                      <embed :src="item.full_file_url" width="100%" height="100%">
                    </object>
                  </video>
                  <audio v-else-if="item.file_type==='audio'" controls>
                    <source :src="item.full_file_url" type="audio/mp3">
                    <embed :src="item.full_file_url" width="100%" height="100%">
                  </audio>
                  <div v-else-if="item.file_type === 'word'" :src="item.file_url">
                    <icon-drive-file size="50"/>
                  </div>
                  <div v-else :src="item.full_file_url">
                    <icon-folder size="50"/>
                  </div>
                </div>
                <div class="file-footer">
                  <div>{{ item.file_size }}</div>
                  <a-space>
                    <a-button v-if="!['image', 'audio'].includes(item.file_type)" type="text" size="mini" @click="viewFile(item)">查看</a-button>
                    <a-button v-if="!item.status" type="text" size="mini" @click="isActivate([item.id], 1)">启用</a-button>
                    <a-button v-else type="text" size="mini" @click="isActivate([item.id], 0)">禁用</a-button>
                    <a-button size="mini" type="text" @click="del([item.id])">删除</a-button>
                  </a-space>
                </div>
              </a-card>
            </a-grid-item>
          </a-grid>
        </a-checkbox-group>
      </a-col>
      <a-col v-else :span="21">
        <a-empty description="暂无文件"/>
      </a-col>
    </a-row>
    <pagination-manage
      v-show="pagination.total > 0"
      :total="pagination.total"
      :current="pagination.current"
      :page-size="pagination.pageSize"
      :page-size-options="[18, 30, 54, 108]"
      @pageCBK="onPageChange"
      @pageSizeCBK="onPageSizeChange"
    />
    <div v-show="fileType" style="text-align: right; margin-top: 10px">
      <a-space>
        <a-button @click="fileCancel()">取消</a-button>
        <a-button type="primary" @click="fileOk()">确定</a-button>
      </a-space>
    </div>

    <FileView ref="fileViewRef" :file-ext="fileExt" />
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, h, compile } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import screenHeight from '@/utils/screen-height';
  import { QueryParams, apiList, apiDel, apiDisable } from '@/api/file';
  import FileUpload from '@/components/file-upload/index.vue';
  import FileView from '@/components/file-upload/view.vue';
  import PaginationManage from '@/components/pagination/index.vue';

  const props = defineProps({
    folder: {
      type: String,
      default: '',
    },
    fileType: {
      type: String,
      default: '',
    },
    ids: {
      type: Array,
      default() {
        return [];
      },
    },
  });
  const emit = defineEmits(['fileCancelCallback', 'fileOkCallback']);

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight();
  const baseQuery = () => {
    return {
      page: 1,
      limit: 18,
      folder: props.folder,
      file_type: props.fileType,
      time_type: 'created_at',
      range_date: [],
    };
  };
  const renderData = ref<any>([]);
  const query = ref(baseQuery());
  const pagination = reactive<any>({});
  const selectedIds = computed<any>({
    get() {
      return props.ids;
    },
    set(val) {

    },
  });
  const rowSelection = reactive({
    type: 'checkbox',
    defaultSelectedRowKeys: [],
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: height,
  });
  const fileBoxStyle = ref({});

  const selectionKeys = ref<string[]>([]); // 选中项ID
  const selectionDatas: any = []; // 选中项
  const checkIds = ref([]); // 选择项ID集合
  const checkAll = ref(false); // 是否全选
  const checkedAllInd = ref(false); // 是否为半选状态
  const checkedIds = ref([]);
  const folders = ref([]);
  const fileTypes = ref([]);

  const fileViewRef = ref();
  const fileExt = ref();

  // 列表
  const fetchData = async (
    params: QueryParams = { ...query.value }
  ) => {
    setLoading(true);
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;

      checkIds.value = data.ids;
      folders.value = data.folders;
      fileTypes.value = data.file_types;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 分页
  const onPageChange = (page: number) => {
    fetchData({ ...query.value, page });
  };
  const onPageSizeChange = (limit: number) => {
    fetchData({ ...query.value, limit });
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 删除
  const del = (row: any[]) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h(compile(message)),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {
            setLoading(false);
          } finally {
            fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 启用/禁用
  const isActivate = async (row: any, isDisable: number) => {
    if (!row.length) {
      selectMsg();
    } else {
      let ids = row;
      if (row.length === 1 && row[0].id) {
        ids = [row[0].id];
      }

      if (isDisable === 0) {
        const title = '禁用文件';
        const message = `禁用文件会对已使用该文件的业务造成影响！<br>确定要禁用文件吗？`;
        Modal.warning({
          title,
          content: () => h(compile(message)),
          closable: true,
          hideCancel: false,
          onOk: (async () => {
            setLoading(true);
            try {
              await apiDisable({
                ids,
                status: isDisable,
              });
            } catch (err) {
              setLoading(false);
            } finally {
              fetchData({...query.value});
              setLoading(false);
            }
          }),
        });
      } else {
        await apiDisable({
          ids,
          status: isDisable,
        });
        fetchData({...query.value});
      }
    }
  };
  // 表单重置
  const reset = async () => {
    //
  };
  // 搜索
  const search = () => {
    query.value.page = 1;
    fetchData({...query.value} as unknown as QueryParams);
  };
  // 刷新
  const refresh = () => {
    query.value = baseQuery();
    fetchData({...query.value});
  };

  // 全选操作 -- 自定义按钮
  const customSelectAll = (value: boolean | any) => {
    checkedAllInd.value = false;
    checkAll.value = value;
    if (value) {
      checkedIds.value = checkIds.value;
    } else {
      checkedIds.value = [];
    }
  };
  // 选择文件
  const selectGroup = (values: any[]) => {
    selectionKeys.value = values;
    const checkedLength= values.length;
    checkAll.value = checkedLength === checkIds.value.length;
    checkedAllInd.value = checkedLength > 0 && checkedLength < checkIds.value.length;
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys.value);
  };
  // 筛选切换
  const filterSelect = (folder: any = '', type: any = '') => {
    query.value.folder = folder;
    query.value.file_type = type;
    fetchData({...query.value});
  };
  const viewFile = (file: any) => {
    fileExt.value = file.file_type;
    const src = file.full_file_url;
    if (src) {
      fileViewRef.value.viewFile(src);
    }
  };
  // const download = (src: string) => {
  //   if (src) {
  //     fileViewRef.value.download(src);
  //   }
  // };

  // 上传回调
  const uploadCallback = () => {
    refresh();
  };

  // 回调
  const fileCancel = () => {
    emit('fileCancelCallback');
  };
  const fileOk = () => {
    if (!selectionKeys.value.length) {
      selectMsg('请选择文件');
    } else {
      renderData.value.forEach((item: any, index: string) => {
        if (selectionKeys.value.includes(item.id)) {
          selectionDatas.push(item);
        }
      });
      emit('fileOkCallback', selectionDatas);
    }
  };

  // 初始化
  const initData = (ids?: any) => {
    rowSelection.defaultSelectedRowKeys = ids;

    if (props.fileType) {
      fileBoxStyle.value = {
        height: `${height-270}px`,
        overflow: 'auto',
      };
    }

    fetchData();
  };

  initData();
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .item {
    margin-bottom: 5px;
  }
  .item .deactive {
    color: var(--color-text-2);
  }
  .file-card {
    position: relative;
    overflow: hidden;
    background: #fff;
  }
  .file-ext {
    position: absolute;
    width: 100px;
    height: 100px;
    top: -66px;
    right: -66px;
    transform: rotate(45deg);
    z-index: 1000;
  }
  .file-ext span {
    display: block;
    position: absolute;
    width: 100px;
    bottom: 0;
    text-align: center;
    font-size: 14px;
    color: #fff;
    background: #C0C4CC;
  }
  .file-footer button {
    padding: 0 6px;
  }
</style>

<style lang="less">
  .file-content img, .file-content video {
    width: 100%;
    height: 100%;
  }
  .file-content audio {
    width: 100%;
  }
</style>
